package testview.zhen.com.myapplication.readsource

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater

import kotlinx.coroutines.*
import okhttp3.*
import testview.zhen.com.myapplication.R
import testview.zhen.com.myapplication.databinding.ActivityOkhttpBinding
import testview.zhen.com.myapplication.readsource.okhttp.OkHttpUtils
import java.io.IOException
import java.util.concurrent.TimeUnit

/**
 * 本Activity主要学习OkHttp用法以及一些源码思路
 */
class OkhttpActivity : AppCompatActivity() {
    private val job = Job()
    private val ioScope = CoroutineScope(Dispatchers.IO + job)
    lateinit var handler: CoroutineExceptionHandler

    companion object {
        val TAG = "OkhttpActivity"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = ActivityOkhttpBinding.inflate(LayoutInflater.from(this))
        setContentView(binding.root)

        handler = CoroutineExceptionHandler { _, exception ->
            run {
                Log.d(TAG, "exception" + exception.message)
            }
        }
        binding.button2.setOnClickListener {
            //创建OkHttpClient对象
            var client = OkHttpClient.Builder()
                    .connectTimeout(5, TimeUnit.SECONDS)
                    .build()
            //创建Request对象
            var request = Request.Builder().url("https://www.wanandroid.com/navi/json").build()
            //同步请求
            ioScope.launch(handler) {
                val requestcall = client.newCall(request)
                requestcall.execute()
                requestcall.execute()
            }
        }
        binding.button3.setOnClickListener {
            //创建OkHttpClient对象
            var client = OkHttpClient.Builder()
                    .connectTimeout(5, TimeUnit.SECONDS)
                    .build()
            //创建Request对象
            var request = Request.Builder().url("https://www.wanandroid.com/navi/json").build()
            //异步请求
            ioScope.launch(handler) {
                client.newCall(request).enqueue(object : Callback {
                    override fun onFailure(call: Call, e: IOException) {
                        Log.d(TAG, "onFailure" + e.message)
                    }

                    override fun onResponse(call: Call, response: Response) {
                        Log.d(TAG, "onResponse" + response.message)
                    }
                })
            }
        }
    }


}
